package com.hs.auth.action;
 
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.hs.auth.AUTHConstant;
import com.hs.auth.model.HsAccount;
import com.hs.auth.model.HsAccrole;
import com.hs.auth.model.HsUserinfo;
import com.hs.auth.service.IUserService;
import com.hs.core.action.BaseAction;
import com.hs.core.db.DBMgr;
import com.hs.core.utils.MD5;
import com.hs.core.utils.PageParam;
import com.hs.core.utils.PageUtil;
@Controller  
public class UserController  extends BaseAction {
    /**
	 * 
	 */
	private static final long serialVersionUID = -354434172898440670L;
	private static final Logger logger = Logger.getLogger(UserController.class);
	private IUserService userService;
	 @Autowired  
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
	 
	 /**
	  * 新增用户
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/auth/userInfo.do", method = RequestMethod.GET)   
     public ModelAndView userInfo(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
         String uid = request.getParameter("uid");//是否存在此参数表明是新增还是修改
         if(StringUtils.isNotEmpty(uid)){
        	 HsAccount info = (HsAccount)userService.findByID(HsAccount.class, new Long(uid));
        	 modelMap.put("accObj", info);
         } 
         List orgList = userService.findList("select a  from HsOrg a where pid!=0");
         List roleList = userService.findList("select a  from HsRole a  ");
         if(null != uid){
        	 DBMgr dbo = DBMgr.getDbUtilInst(request.getSession().getServletContext());
        	 List userroleList=dbo.queryList("select roleid from Hs_Accrole a where a.accid=?", new Object[]{new Long(uid)});
        	 String roleid = "";
        	 for(int i=0; i<userroleList.size(); i++){
        		 Map obj = (Map)userroleList.get(i);
        		 roleid = roleid + obj.get("roleid") + ",";
        	 }
        	 modelMap.put("userrole", roleid);
         }
         modelMap.put("orgList", orgList);
         modelMap.put("roleList", roleList);
		 return new ModelAndView("common/auth/userInfo",modelMap);
		 
	 }
	 /**
	  * 用户保存操作
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/auth/saveUser.do", method = RequestMethod.POST)   
     public ModelAndView saveUser(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String uid = request.getParameter("loginid");//是否存在此参数表明是新增还是修改
		 String accid = request.getParameter("id");//是否存在此参数表明是新增还是修改
		 String userid = request.getParameter("userid");//是否存在此参数表明是新增还是修改
		 String username = request.getParameter("username");
		 String pwd = request.getParameter("pwd");
		 String shengri = request.getParameter("shengri");
		 String sex = request.getParameter("sex");
		 String phone = request.getParameter("phone");
		 String handphone = request.getParameter("handphone");
		 String zuigxl = request.getParameter("zuigxl");
		 String biyyx = request.getParameter("school");
		 String zhicheng = request.getParameter("zhicheng");
		 String email = request.getParameter("email");
		 String postnum = request.getParameter("postno"); 
		 String address = request.getParameter("postaddress");
		 String status = request.getParameter("status");
		 String[] role = request.getParameterValues("role");
		 HsUserinfo info = null;
		 HsAccount acc = null;
		 logger.debug("uid:" + uid);
         if(StringUtils.isNotEmpty(accid)){
        	 acc = (HsAccount)userService.findByID(HsAccount.class, new Long(accid));
         }else{
        	 acc = new HsAccount();
        	 acc.setLoginid(uid);
         }
         if(StringUtils.isNotEmpty(userid)){
        	 info = (HsUserinfo)userService.findByID(HsUserinfo.class, new Long(userid));
         }else{
        	 info = new HsUserinfo();
         }
         logger.debug("accid:" + accid);
         if(StringUtils.isNotEmpty(pwd))
        	 acc.setPassword(MD5.md5(pwd));
         acc.setStatus(Long.parseLong(status)); 
        
         acc.setUserinfo(info);
         acc.setCreatetime(new Date());
         info.setAddress(address);
         info.setUserage(shengri);
         info.setPhone(phone);
         info.setBiyeyx(biyyx);
         info.setEmail(email);
         info.setHandphone(handphone);
         info.setPostnum(postnum);
         info.setUsername(username);
         info.setCreatedate(new Date());
         if(StringUtils.isNotEmpty(sex))
        	 info.setUsersex(new Long(sex));
         info.setZuigxl(zuigxl); 
         info.setZhicheng(new Long(zhicheng));
         
         
         userService.saveObject(info); 
         userService.saveObject(acc);
         DBMgr dbo = DBMgr.getDbUtilInst(request.getSession().getServletContext());
         dbo.update("delete from HS_ACCROLE where ACCID=?", new Object[]{acc.getId()});
         for(int i=0; i<role.length; i++){
        	 dbo.update("insert into HS_ACCROLE (id,roleid,accid) values(SEQ_HS_ACCROLE_ID.nextval,?,?)", new Object[]{role[i],acc.getId()});
		 }
         modelMap.put("accObj", acc);
         modelMap.put("flag", "fresh");
         List orgList =  userService.findList("select a  from HsOrg a where pid!=0");
         List roleList = userService.findList("select a  from HsRole a ");
         if(null != acc){
        	 logger.debug("uid2:" + accid);
        	 dbo = DBMgr.getDbUtilInst(request.getSession().getServletContext());
        	 List userroleList=dbo.queryList("select roleid from Hs_Accrole a where a.accid=?", new Object[]{acc.getId()});
        	 String roleid = "";
        	 for(int i=0; i<userroleList.size(); i++){
        		 Map obj = (Map)userroleList.get(i);
        		 roleid = roleid + obj.get("roleid") + ",";
        	 }
        	 modelMap.put("userrole", roleid);
         }
         modelMap.put("orgList", orgList);
         modelMap.put("roleList", roleList);
         return new ModelAndView("common/auth/userInfo",modelMap);  
		 
	 }
	 /**
	  * 用户管理首页
	  * @param request
	  * @param response
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	@RequestMapping("/auth/userFrame.do")   
	public ModelAndView userFrame(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException { 
		return new ModelAndView("common/auth/userFrame");  
	}
	 /**
	  * 用户列表
	  * @param request
	  * @param response
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	@RequestMapping("/auth/listUser.do")   
	public ModelAndView listUser(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException { 
		PageParam pageParam = new  PageParam(request,"auth/listUser.do");
		StringBuffer buffer = new StringBuffer(); 
	    
		
	    //排序结束
		PageUtil pageUtil = null;
		StringBuffer searchBuffer = new StringBuffer(" select a from HsAccount a where 1=1   ");
		//StringBuffer searchBuffer = new StringBuffer(" select a from HbpZhu a where 1=1 ");
		
		String loginId = request.getParameter("loginId"); 
		String userName = request.getParameter("userName");  

		 
		if(StringUtils.isNotBlank(userName)){
			searchBuffer.append(" and a.userinfo.username like ?");
			pageParam.getConditionMap().put("userName", userName);
			request.setAttribute("userName", userName);
		}   
		if(StringUtils.isNotBlank(loginId)){
			searchBuffer.append(" and a.loginid ='").append(loginId).append("'");
			pageParam.getConditionMap().put("loginId", loginId);
			request.setAttribute("loginId", loginId);
		}  
		 
		 //searchBuffer.append(" order by a.loginid");
		Map data = new HashMap();
		pageParam.setSearchSql(searchBuffer.toString());
		pageUtil = userService.getAccList(pageParam);	
		data.put("dataList", pageUtil);   
 		return new ModelAndView("common/auth/userList",data);  
	}
	 
	 /**
	  * 修改用户信息
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/auth/modifyUserinfo.do")   
    public ModelAndView modifyUserinfo(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String uid = request.getParameter("uid");//是否存在此参数表明是新增还是修改
         if(StringUtils.isNotEmpty(uid)){
        	 HsAccount info = (HsAccount)userService.findByID(HsAccount.class, new Long(uid));
        	 modelMap.put("accObj", info);
         } 
         List orgList = userService.findList("select a  from HsOrg a where pid!=0");
         List roleList = userService.findList("select a  from HsRole a  ");
         if(null != uid){
        	 DBMgr dbo = DBMgr.getDbUtilInst(request.getSession().getServletContext());
        	 List userroleList=dbo.queryList("select roleid from Hs_Accrole a where a.accid=?", new Object[]{new Long(uid)});
        	 Map obj = (Map)userroleList.get(0);
        	 modelMap.put("userrole", obj.get("roleid")+"");
         }
         modelMap.put("orgList", orgList);
         modelMap.put("roleList", roleList);
         return new ModelAndView("common/auth/modifyUserinfo",modelMap);
	 } 
	 /**
	  * 用户保存操作
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/auth/saveUserinfo.do", method = RequestMethod.POST)   
     public ModelAndView saveUserinfo(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String uid = request.getParameter("loginid");//是否存在此参数表明是新增还是修改
		 String accid = request.getParameter("id");//是否存在此参数表明是新增还是修改
		 String userid = request.getParameter("userid");//是否存在此参数表明是新增还是修改
		 String username = request.getParameter("username");
		 String pwd = request.getParameter("pwd");
		 String shengri = request.getParameter("shengri");
		 String sex = request.getParameter("sex");
		 String phone = request.getParameter("phone");
		 String handphone = request.getParameter("handphone");
		 String zuigxl = request.getParameter("zuigxl");
		 String biyyx = request.getParameter("school");
		 String zhicheng = request.getParameter("zhicheng");
		 String email = request.getParameter("email");
		 String postnum = request.getParameter("postno"); 
		 String address = request.getParameter("postaddress");
		 String roleid = request.getParameter("roleid");
		 String status = request.getParameter("status");
		 
		 HsUserinfo info = null;
		 HsAccount acc = null;
         logger.debug("accid:" + accid);
         if(StringUtils.isNotEmpty(accid)){
        	 acc = (HsAccount)userService.findByID(HsAccount.class, new Long(accid));
         }else{
        	 acc = new HsAccount();
        	 acc.setLoginid(uid);
         }
         if(StringUtils.isNotEmpty(userid)){
        	 info = (HsUserinfo)userService.findByID(HsUserinfo.class, new Long(userid));
         }else{
        	 info = new HsUserinfo();
         }
         logger.debug("accid:" + accid);
         if(StringUtils.isNotEmpty(pwd))
        	 acc.setPassword(MD5.md5(pwd));
         acc.setStatus(Long.parseLong(status)); 
        
         acc.setUserinfo(info);
         acc.setCreatetime(new Date());
         info.setAddress(address);
         info.setUserage(shengri);
         info.setPhone(phone);
         info.setBiyeyx(biyyx);
         info.setEmail(email);
         info.setHandphone(handphone);
         info.setPostnum(postnum);
         info.setUsername(username);
         info.setCreatedate(new Date());
         if(StringUtils.isNotEmpty(sex))
        	 info.setUsersex(new Long(sex));
         info.setZuigxl(zuigxl); 
         info.setZhicheng(new Long(zhicheng));
         
         
         userService.saveObject(info); 
         userService.saveObject(acc);
         DBMgr dbo = DBMgr.getDbUtilInst(request.getSession().getServletContext());
         dbo.update("delete from HS_ACCROLE where ACCID=?", new Object[]{acc.getId()});
         dbo.update("insert into HS_ACCROLE (id,roleid,accid) values(SEQ_HS_ACCROLE_ID.nextval,?,?)", new Object[]{roleid,acc.getId()});
         modelMap.put("accObj", acc);
         modelMap.put("flag", "fresh");
         List orgList =  userService.findList("select a  from HsOrg a where pid!=0");
         List roleList = userService.findList("select a  from HsRole a ");
         modelMap.put("orgList", orgList);
         modelMap.put("roleList", roleList);
         return new ModelAndView("common/auth/modifyUserinfo",modelMap);  
		 
	 }
}
